package cn.edu.lingnan.lsqn.controller;

import java.util.Date;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import cn.cdahua.basic.model.Pager;
import cn.cdahua.basic.model.SystemContext;
import cn.edu.lingnan.lsqn.model.LsqnException;
import cn.edu.lingnan.lsqn.model.Song;
import cn.edu.lingnan.lsqn.model.User;
import cn.edu.lingnan.lsqn.service.ISongService;

@Controller
@RequestMapping("/song")
public class SongController {

	@Autowired
	private ISongService songService;
	
	@RequestMapping(value= {"/"})
	public String index(){
		return "song/song";
	}
	@RequestMapping(value= {"/list"})
	public String list(Model model,HttpSession session){
		SystemContext.setOrder("id");
		SystemContext.setSort("desc");
		Boolean isStudent = (boolean) session.getAttribute("isStudent");
		Pager<Song> songs=null;
		try{
			if(isStudent!=null && isStudent)
				songs = songService.findByUserId(((User)session.getAttribute("loginUser")).getId());
			else
				songs = songService.find();
			model.addAttribute("datas", songs);
		}finally{
			SystemContext.removeOrder();
			SystemContext.removeSort();
		}
		return "comm/songlist";
	}
	@RequestMapping(value= {"/add"})
	public String add(String name,String message,@RequestParam String vc,HttpSession session){
		
		String cc = (String) session.getAttribute("cc");
		if(!cc.equals(vc)) throw new LsqnException("验证码错误");
		
		Song s = new Song();
		User user = (User) session.getAttribute("loginUser");
		if(user==null) throw new LsqnException("您还没有登录，不允许该操作");
		s.setName(name);
		s.setMessage(message);
		s.setUser(user);
		s.setCreateDate(new Date());
		s.setStatus(0);
		songService.add(s);
		return "redirect:list";
	}
	@RequestMapping(value= {"/update/{id}"})
	public String update(@PathVariable int id){
		songService.update(id);
		return "redirect:/song/list";
	}
	@RequestMapping(value= {"/delete/{id}"})
	public String delete(@PathVariable int id){
		songService.delete(id);
		return "redirect:/song/list";
	}
	
}
